<template>
  <div class="payment-container">
    <!-- 顶部信息栏 -->
    <div class="header-card bg-white rounded-lg shadow-md p-6 mb-8">
      <div class="flex flex-col md:flex-row items-center justify-between gap-6">
        <!-- 供应商信息区 -->
        <div class="flex items-center gap-4">
          <label class="required text-gray-700 font-medium">供应商：</label>
          <el-input
            v-model="selectedSupplier.name"
            readonly
            placeholder="点击选择供应商"
            @click="supplierDialogVisible = true"
            class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            style="width: 220px"
          />
          <label class="text-gray-700 font-medium">总欠款：</label>
          <el-input
            v-model="totalDebt"
            readonly
            placeholder="0.00"
            style="width: 120px"
            class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
          />
          <label class="required text-gray-700 font-medium">付款人：</label>
          <el-select
            v-model="payer"
            placeholder="选择付款人"
            @change="handlePayerChange"
            class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            style="width: 160px"
          >
            <el-option
              v-for="item in payerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <label class="required text-gray-700 font-medium">单据日期：</label>
          <el-date-picker
            v-model="paymentDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="点击选择日期"
            trigger="click"
            class="border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
            style="width: 160px"
          />
        </div>

        <!-- 附件 & 单据编号 -->
        <div class="flex items-end gap-4">
          <el-upload
            class="upload-btn"
            :file-list="attachments"
            action="#"
            :on-preview="handlePreview"
          >
            <el-button
              type="text"
              class="text-blue-600 hover:text-blue-800 flex items-center"
            >
              <el-icon><UploadFilled /></el-icon>
              <span class="ml-1">上传附件</span>
            </el-button>
          </el-upload>
          <el-tag class="bg-blue-100 text-blue-800 text-sm">
            {{ paymentNo }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 结算账户表格 -->
    <div class="grid grid-cols-1 gap-8">
      <div class="bg-white rounded-lg shadow-md p-6 overflow-x-auto">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-semibold text-gray-800">结算账户</h3>
          <el-button
            type="success"
            icon="el-icon-plus"
            @click="addSettlementRow"
            class="text-sm px-4"
            >新增行</el-button
          >
        </div>
        <el-table
          :data="settlementTable"
          border
          style="width: 100%; min-width: 800px"
          stripe
          class="text-sm"
        >
          <el-table-column label="*结算账户" prop="account" width="120">
            <template #default="scope">
              <div
                class="cursor-pointer text-blue-600 hover:text-blue-800"
                @click="openAccountDialog(scope.row)"
              >
                {{ getAccountLabel(scope.row.account) || "请选择" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="*付款金额" prop="amount" width="100">
            <template #default="scope">
              <el-input
                v-model.number="scope.row.amount"
                type="number"
                size="small"
                required
              />
            </template>
          </el-table-column>
          <el-table-column label="结算方式" prop="method" width="100">
            <template #default="scope">
              <div
                class="cursor-pointer text-blue-600 hover:text-blue-800"
                @click="openMethodDialog(scope.row)"
              >
                {{ getMethodLabel(scope.row.method) || "请选择" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="结算号" prop="no" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.no" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="deleteSettlementRow(scope.row)"
                size="small"
                text
                hover-effect="light"
              />
            </template>
          </el-table-column>
          <template #footer>
            <el-table-row>
              <el-table-cell>合计：</el-table-cell>
              <el-table-cell>{{ settlementTotal }}</el-table-cell>
              <el-table-cell colspan="4"></el-table-cell>
            </el-table-row>
          </template>
        </el-table>
      </div>

      <!-- 源单表格 -->
      <div class="bg-white rounded-lg shadow-md p-6 overflow-x-auto">
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-xl font-semibold text-gray-800">源单信息</h3>
          <div class="flex gap-2">
            <el-button
              type="primary"
              class="text-sm px-4"
              @click="openSourceDialog"
              >选择源单</el-button
            >
            <el-button type="success" class="text-sm px-4">自动核销</el-button>
          </div>
        </div>
        <el-table
          :data="sourceTable"
          border
          style="width: 100%; min-width: 1200px"
          stripe
          class="text-sm"
        >
          <el-table-column label="源单编号" prop="sourceNo" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.sourceNo" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="业务类别" prop="businessType" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.businessType" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="单据日期" prop="docDate" width="120">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.docDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="单据金额" prop="docAmount" width="100">
            <template #default="scope">
              <el-input
                v-model.number="scope.row.docAmount"
                type="number"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="已核销金额" prop="settledAmount" width="120">
            <template #default="scope">
              <el-input
                v-model.number="scope.row.settledAmount"
                type="number"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="未核销金额"
            prop="unsettledAmount"
            width="120"
          >
            <template #default="scope">
              <el-input
                v-model.number="scope.row.unsettledAmount"
                type="number"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="*本次核销金额"
            prop="currentSettle"
            width="120"
          >
            <template #default="scope">
              <el-input
                v-model.number="scope.row.currentSettle"
                type="number"
                size="small"
                required
              />
            </template>
          </el-table-column>
          <el-table-column label="单据备注" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <div class="flex items-center gap-2">
                <!-- 添加行按钮（绿色） -->
                <el-button
                  type="success"
                  icon="el-icon-plus"
                  @click="addSourceRow(scope.$index)"
                  size="small"
                  text="添加"
                  hover-effect="light"
                />

                <!-- 删除行按钮（红色） -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteSourceRow(scope.row)"
                  size="small"
                  text
                  hover-effect="light"
                />
              </div>
            </template>
          </el-table-column>
          <template #footer>
            <el-table-row>
              <el-table-cell>合计：</el-table-cell>
              <el-table-cell>{{ sourceTotals.totalDocAmount }}</el-table-cell>
              <el-table-cell>{{ sourceTotals.totalSettled }}</el-table-cell>
              <el-table-cell>{{ sourceTotals.totalUnsettled }}</el-table-cell>
              <el-table-cell>{{ sourceTotals.totalCurrent }}</el-table-cell>
              <el-table-cell colspan="3"></el-table-cell>
            </el-table-row>
          </template>
        </el-table>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="mt-8 bg-white rounded-lg shadow-md p-6">
      <div
        class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6"
      >
        <div class="flex flex-col sm:flex-row gap-4">
          <div class="flex items-center gap-2">
            <label class="text-gray-700 font-medium">整单折扣：</label>
            <el-input
              v-model.number="discount"
              type="number"
              style="width: 160px"
              size="small"
            />
          </div>
          <div class="flex items-center gap-2">
            <label class="text-gray-700 font-medium">本次预付款：</label>
            <el-input
              v-model.number="prePayment"
              type="number"
              style="width: 160px"
              readonly
              size="small"
            />
          </div>
          <el-button
            type="text"
            size="small"
            class="text-blue-600 hover:text-blue-800"
          >
            自定义字段
          </el-button>
        </div>
        <div class="flex justify-end gap-2">
          <el-button type="primary" class="text-sm px-4">保存并新增</el-button>
          <el-button type="success" class="text-sm px-4">保存</el-button>
          <el-button type="info" class="text-sm px-4">审核</el-button>
          <el-button
            type="text"
            class="text-sm text-gray-600 hover:text-gray-800 px-4"
          >
            历史单据
          </el-button>
          <el-button
            type="text"
            class="text-sm text-gray-600 hover:text-gray-800 px-4"
          >
            操作日志
          </el-button>
        </div>
      </div>
    </div>

    <!-- 供应商选择弹窗 -->
    <el-dialog
      title="选择供应商"
      v-model="supplierDialogVisible"
      width="800px"
      class="dialog-custom"
    >
      <el-form :model="supplierQuery" inline label-width="80px" class="mb-4">
        <el-form-item label="类别">
          <el-select v-model="supplierQuery.category" size="small">
            <el-option label="核心供应商" value="core"></el-option>
            <el-option label="普通供应商" value="normal"></el-option>
            <el-option label="临时供应商" value="temp"></el-option>
            <el-option label="服务供应商" value="service"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查询">
          <el-input
            v-model="supplierQuery.keyword"
            placeholder="编号/名称/联系人/电话/税号"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="supplierQuery.showDisabled" size="small">
            显示禁用供应商
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchSuppliers" size="small">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="supplierList"
        border
        style="width: 100%"
        @selection-change="handleSupplierSelection"
        stripe
        class="text-sm"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="类别" prop="category" width="100">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)" size="mini">{{
              getCategoryLabel(scope.row.category)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="编号" prop="code" width="120" />
        <el-table-column label="名称" prop="name" width="180" />
        <el-table-column label="联系人" prop="contact" width="100" />
        <el-table-column label="手机" prop="phone" width="120" />
        <el-table-column label="地址" prop="address" width="200" />
        <el-table-column label="应付余额" prop="balance" width="120">
          <template #default="scope">
            <span class="text-red-500">{{ scope.row.balance.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="银行账号" prop="bankAccount" width="180" />
        <el-table-column label="税号" prop="taxNo" width="180" />
        <el-table-column label="开户银行" prop="bankName" width="180" />
      </el-table>
      <div class="dialog-footer flex justify-between items-center mt-4">
        <el-pagination
          @size-change="(val) => (supplierPageSize = val)"
          @current-change="(val) => (supplierPage = val)"
          :current-page="supplierPage"
          :page-sizes="[10, 50, 100]"
          :page-size="supplierPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="supplierTotal"
          size="small"
        />
        <div class="flex gap-2">
          <el-button type="primary" @click="confirmSupplier" size="small">
            确定
          </el-button>
          <el-button @click="supplierDialogVisible = false" size="small">
            取消
          </el-button>
          <el-button
            type="text"
            size="small"
            class="text-blue-600 hover:text-blue-800"
            @click="openAddSupplierDialog"
          >
            新增供应商
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 新增供应商弹窗 -->
    <el-dialog
      title="新增供应商"
      v-model="addSupplierDialogVisible"
      width="600px"
      class="dialog-custom"
    >
      <el-form
        :model="newSupplier"
        label-width="100px"
        class="p-4"
        ref="supplierForm"
      >
        <el-form-item label="*供应商编号" prop="code">
          <el-input v-model="newSupplier.code" size="small" required />
        </el-form-item>
        <el-form-item label="*供应商名称" prop="name">
          <el-input v-model="newSupplier.name" size="small" required />
        </el-form-item>
        <el-form-item label="*供应商类别" prop="category">
          <el-select v-model="newSupplier.category" size="small" required>
            <el-option label="核心供应商" value="core"></el-option>
            <el-option label="普通供应商" value="normal"></el-option>
            <el-option label="临时供应商" value="temp"></el-option>
            <el-option label="服务供应商" value="service"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="newSupplier.contact" size="small" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="newSupplier.phone" size="small" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="newSupplier.address" size="small" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="newSupplier.bankAccount" size="small" />
        </el-form-item>
        <el-form-item label="税号" prop="taxNo">
          <el-input v-model="newSupplier.taxNo" size="small" />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="newSupplier.bankName" size="small" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="addSupplierDialogVisible = false" size="small">
            取消
          </el-button>
          <el-button type="primary" @click="saveNewSupplier" size="small">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增职员弹窗（付款人扩展） -->
    <el-dialog
      title="新增职员"
      v-model="addEmployeeDialogVisible"
      width="400px"
      class="dialog-custom"
    >
      <el-form
        :model="newEmployee"
        label-width="80px"
        class="p-4"
        ref="employeeForm"
      >
        <el-form-item label="*职员编号" prop="code">
          <el-input v-model="newEmployee.code" size="small" required />
        </el-form-item>
        <el-form-item label="*职员名称" prop="name">
          <el-input v-model="newEmployee.name" size="small" required />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="newEmployee.department" size="small" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="newEmployee.phone" size="small" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="addEmployeeDialogVisible = false" size="small">
            取消
          </el-button>
          <el-button type="primary" @click="saveNewEmployee" size="small">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结算账户选择对话框 -->
    <el-dialog
      title="选择结算账户"
      v-model="accountDialogVisible"
      width="400px"
    >
      <div class="p-4">
        <el-input
          v-model="accountSearchKeyword"
          placeholder="搜索结算账户"
          size="small"
          class="mb-4"
        />
        <el-radio-group v-model="selectedAccount">
          <el-radio
            v-for="item in filteredAccountOptions"
            :key="item.value"
            :label="item.value"
            class="block mb-2"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="accountDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAccount">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结算方式选择对话框 -->
    <el-dialog title="选择结算方式" v-model="methodDialogVisible" width="400px">
      <div class="p-4">
        <el-input
          v-model="methodSearchKeyword"
          placeholder="搜索结算方式"
          size="small"
          class="mb-4"
        />
        <el-radio-group v-model="selectedMethod">
          <el-radio
            v-for="item in filteredMethodOptions"
            :key="item.value"
            :label="item.value"
            class="block mb-2"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="methodDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMethod">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择源单对话框 -->
    <el-dialog title="选择源单" v-model="sourceDialogVisible" width="900px">
      <el-form :model="sourceQuery" inline label-width="80px" class="mb-4">
        <el-form-item label="业务类型">
          <el-select v-model="sourceQuery.businessType" size="small">
            <el-option label="采购订单" value="purchase"></el-option>
            <el-option label="应付单" value="payment"></el-option>
            <el-option label="其他应付" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select v-model="sourceQuery.status" size="small">
            <el-option label="全部" value=""></el-option>
            <el-option label="未核销" value="unsettled"></el-option>
            <el-option label="部分核销" value="partial"></el-option>
            <el-option label="已核销" value="settled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="sourceQuery.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
          />
        </el-form-item>
        <el-form-item label="查询">
          <el-input
            v-model="sourceQuery.keyword"
            placeholder="单号/供应商"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchSourceBills" size="small">
            查询
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="sourceBillList"
        border
        style="width: 100%"
        @selection-change="handleSourceSelection"
        stripe
        class="text-sm"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="单据编号" prop="billNo" width="120" />
        <el-table-column label="业务类型" prop="businessType" width="100">
          <template #default="scope">
            <el-tag
              :type="getBusinessType(scope.row.businessType)"
              size="mini"
              >{{ getBusinessTypeLabel(scope.row.businessType) }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="单据日期" prop="billDate" width="120" />
        <el-table-column label="供应商" prop="supplier" width="150" />
        <el-table-column label="单据金额" prop="amount" width="100" />
        <el-table-column label="已核销金额" prop="settledAmount" width="100" />
        <el-table-column label="未核销金额" prop="unsettledAmount" width="100">
          <template #default="scope">
            <span class="text-red-500">{{
              scope.row.unsettledAmount.toFixed(2)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单据状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="mini">{{
              getStatusLabel(scope.row.status)
            }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer flex justify-between items-center mt-4">
        <el-pagination
          @size-change="(val) => (sourcePageSize = val)"
          @current-change="(val) => (sourcePage = val)"
          :current-page="sourcePage"
          :page-sizes="[10, 50, 100]"
          :page-size="sourcePageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="sourceTotal"
          size="small"
        />
        <div class="flex gap-2">
          <el-button type="primary" @click="confirmSource" size="small">
            确定
          </el-button>
          <el-button @click="sourceDialogVisible = false" size="small">
            取消
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import {
  ElDialog,
  ElTable,
  ElTableColumn,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElButton,
  ElTag,
  ElPagination,
  ElUpload,
  UploadFilled,
  ElMessage,
} from "element-plus";

// 供应商信息
const selectedSupplier = ref({ name: "" });
const supplierDialogVisible = ref(false);
const addSupplierDialogVisible = ref(false);
const supplierQuery = reactive({
  category: "",
  keyword: "",
  showDisabled: false,
});
const supplierList = ref([]);
const supplierTotal = ref(20);
const supplierPage = ref(1);
const supplierPageSize = ref(10);
const totalDebt = ref(0.0);
const newSupplier = reactive({
  code: "",
  name: "",
  category: "normal",
  contact: "",
  phone: "",
  address: "",
  bankAccount: "",
  taxNo: "",
  bankName: "",
});

// 付款人配置
const payerOptions = ref([
  { label: "(空)", value: "" },
  { label: "老板", value: "boss" },
  { label: "财务-玲", value: "finance-ling" },
  { label: "采购-小陈", value: "purchase-xc" },
  { label: "采购-小王", value: "purchase-xw" },
  { label: "销售-小李", value: "sales-xl" },
  { label: "+新增职员", value: "add" },
]);
const payer = ref("");
const addEmployeeDialogVisible = ref(false);
const newEmployee = reactive({
  code: "",
  name: "",
  department: "",
  phone: "",
});

// 单据信息
const paymentDate = ref(new Date().toISOString().slice(0, 10));
const paymentNo = ref("FKD20250625001");
const attachments = ref([]);

// 结算账户表格
const settlementTable = ref([
  {
    id: 1,
    account: "",
    amount: 0,
    method: "",
    no: "",
    remark: "",
  },
]);

// 源单表格
const sourceTable = ref([
  {
    id: 1,
    sourceNo: "",
    businessType: "",
    docDate: "",
    docAmount: 0,
    settledAmount: 0,
    unsettledAmount: 0,
    currentSettle: 0,
    remark: "",
  },
]);

// 底部字段
const discount = ref(0.0);
const prePayment = ref(0.0);

// 结算配置
const settlementAccountOptions = ref([
  { label: "1001 现金", value: "1001" },
  { label: "1002 银行存款", value: "1002" },
  { label: "1003 微信支付", value: "1003" },
  { label: "1004 支付宝", value: "1004" },
  { label: "1005 其他货币资金", value: "1005" },
  { label: "1122 应收账款", value: "1122" },
  { label: "2202 应付账款", value: "2202" },
  { label: "2203 预收账款", value: "2203" },
  { label: "2204 预付账款", value: "2204" },
]);
const settlementMethodOptions = ref([
  { label: "现金", value: "cash" },
  { label: "支票", value: "check" },
  { label: "电汇", value: "telegraphic" },
  { label: "汇票", value: "draft" },
  { label: "信用证", value: "lc" },
  { label: "微信支付", value: "wechat" },
  { label: "支付宝", value: "alipay" },
  { label: "银行转账", value: "bank" },
  { label: "其他", value: "other" },
]);

// 对话框状态
const accountDialogVisible = ref(false);
const selectedAccount = ref("");
const accountSearchKeyword = ref("");
let currentSettlementRow = null;

const methodDialogVisible = ref(false);
const selectedMethod = ref("");
const methodSearchKeyword = ref("");
let currentMethodRow = null;

// 源单对话框
const sourceDialogVisible = ref(false);
const sourceQuery = reactive({
  businessType: "",
  status: "",
  dateRange: [],
  keyword: "",
});
const sourceBillList = ref([]);
const sourceTotal = ref(30);
const sourcePage = ref(1);
const sourcePageSize = ref(10);
const selectedSourceBills = ref([]);

// 计算属性
const settlementTotal = computed(() =>
  settlementTable.value.reduce((sum, item) => sum + item.amount, 0)
);

const sourceTotals = computed(() => ({
  totalDocAmount: sourceTable.value.reduce(
    (sum, item) => sum + item.docAmount,
    0
  ),
  totalSettled: sourceTable.value.reduce(
    (sum, item) => sum + item.settledAmount,
    0
  ),
  totalUnsettled: sourceTable.value.reduce(
    (sum, item) => sum + item.unsettledAmount,
    0
  ),
  totalCurrent: sourceTable.value.reduce(
    (sum, item) => sum + item.currentSettle,
    0
  ),
}));

const filteredAccountOptions = computed(() =>
  accountSearchKeyword.value
    ? settlementAccountOptions.value.filter(
        (item) =>
          item.label.includes(accountSearchKeyword.value) ||
          item.value.includes(accountSearchKeyword.value)
      )
    : settlementAccountOptions.value
);

const filteredMethodOptions = computed(() =>
  methodSearchKeyword.value
    ? settlementMethodOptions.value.filter(
        (item) =>
          item.label.includes(methodSearchKeyword.value) ||
          item.value.includes(methodSearchKeyword.value)
      )
    : settlementMethodOptions.value
);

// 辅助函数
const getAccountLabel = (value) =>
  settlementAccountOptions.value.find((item) => item.value === value)?.label ||
  "";

const getMethodLabel = (value) =>
  settlementMethodOptions.value.find((item) => item.value === value)?.label ||
  "";

const getCategoryLabel = (value) => {
  const map = {
    core: "核心供应商",
    normal: "普通供应商",
    temp: "临时供应商",
    service: "服务供应商",
  };
  return map[value] || value;
};

const getCategoryType = (value) => {
  const map = {
    core: "success",
    normal: "info",
    temp: "warning",
    service: "primary",
  };
  return map[value] || "default";
};

const getBusinessTypeLabel = (value) => {
  const map = {
    purchase: "采购订单",
    payment: "应付单",
    other: "其他应付",
  };
  return map[value] || value;
};

const getBusinessType = (value) => {
  const map = {
    purchase: "primary",
    payment: "success",
    other: "info",
  };
  return map[value] || "default";
};

const getStatusLabel = (value) => {
  const map = {
    unsettled: "未核销",
    partial: "部分核销",
    settled: "已核销",
  };
  return map[value] || value;
};

const getStatusType = (value) => {
  const map = {
    unsettled: "danger",
    partial: "warning",
    settled: "success",
  };
  return map[value] || "default";
};

// 供应商方法
const fetchSuppliers = () => {
  // 模拟接口请求
  supplierList.value = [
    {
      category: "core",
      code: "S001",
      name: "核心供应商A",
      contact: "王经理",
      phone: "138****1234",
      address: "上海市浦东新区张江高科技园区",
      balance: 15000.5,
      bankAccount: "6222021202001234567",
      taxNo: "91310115MA1H8XXXXXX",
      bankName: "中国工商银行上海市张江支行",
    },
    {
      category: "normal",
      code: "S002",
      name: "普通供应商B",
      contact: "李主管",
      phone: "139****5678",
      address: "北京市海淀区中关村大街",
      balance: 8500.25,
      bankAccount: "6228480038888888888",
      taxNo: "91110108MA01XXXXXX",
      bankName: "中国农业银行北京市中关村支行",
    },
    {
      category: "temp",
      code: "S003",
      name: "临时供应商C",
      contact: "赵先生",
      phone: "137****9012",
      address: "广州市天河区珠江新城",
      balance: 3200.0,
      bankAccount: "6214830200000000000",
      taxNo: "91440101MA5XXXXXX",
      bankName: "招商银行广州市天河支行",
    },
    {
      category: "service",
      code: "S004",
      name: "服务供应商D",
      contact: "孙小姐",
      phone: "136****3456",
      address: "深圳市南山区科技园",
      balance: 21000.75,
      bankAccount: "6230520120000000000",
      taxNo: "91440300MA5XXXXXX",
      bankName: "中国建设银行深圳市南山支行",
    },
  ];
};

const handleSupplierSelection = (val) => {
  selectedSupplier.value = val[0] || {};
};

const confirmSupplier = () => {
  if (selectedSupplier.value.name) {
    totalDebt.value = selectedSupplier.value.balance || 0.0;

    // 自动填充源单表格中的供应商信息
    if (sourceTable.value.length > 0) {
      sourceTable.value.forEach((row) => {
        row.supplier = selectedSupplier.value.name;
      });
    }
  }
  supplierDialogVisible.value = false;
};

const openAddSupplierDialog = () => {
  // 重置表单
  newSupplier.code = "";
  newSupplier.name = "";
  newSupplier.category = "normal";
  newSupplier.contact = "";
  newSupplier.phone = "";
  newSupplier.address = "";
  newSupplier.bankAccount = "";
  newSupplier.taxNo = "";
  newSupplier.bankName = "";

  addSupplierDialogVisible.value = true;
};

const saveNewSupplier = () => {
  // 简单表单验证
  if (!newSupplier.code || !newSupplier.name) {
    ElMessage.warning("供应商编号和名称为必填项");
    return;
  }

  // 添加到供应商列表
  supplierList.value.push({
    ...newSupplier,
    balance: 0.0,
  });

  ElMessage.success("供应商添加成功");
  addSupplierDialogVisible.value = false;
};

// 付款人方法
const handlePayerChange = (val) => {
  if (val === "add") {
    addEmployeeDialogVisible.value = true;
    payer.value = ""; // 重置选择
  } else {
    payer.value = val;
  }
};

const saveNewEmployee = () => {
  // 简单校验
  if (!newEmployee.code || !newEmployee.name) {
    ElMessage.warning("职员编号和名称为必填项！");
    return;
  }

  // 添加到付款人选项
  payerOptions.value.splice(payerOptions.value.length - 1, 0, {
    label: newEmployee.name,
    value: newEmployee.code,
  });

  ElMessage.success("职员添加成功");
  addEmployeeDialogVisible.value = false;

  // 清空表单
  newEmployee.code = "";
  newEmployee.name = "";
  newEmployee.department = "";
  newEmployee.phone = "";
};

// 结算账户方法
const openAccountDialog = (row) => {
  currentSettlementRow = row;
  selectedAccount.value = row.account;
  accountSearchKeyword.value = "";
  accountDialogVisible.value = true;
};

const confirmAccount = () => {
  if (currentSettlementRow) {
    currentSettlementRow.account = selectedAccount.value;
  }
  accountDialogVisible.value = false;
};

// 结算方式方法
const openMethodDialog = (row) => {
  currentMethodRow = row;
  selectedMethod.value = row.method;
  methodSearchKeyword.value = "";
  methodDialogVisible.value = true;
};

const confirmMethod = () => {
  if (currentMethodRow) {
    currentMethodRow.method = selectedMethod.value;
  }
  methodDialogVisible.value = false;
};

// 源单对话框方法
const openSourceDialog = () => {
  if (!selectedSupplier.value.name) {
    ElMessage.warning("请先选择供应商");
    return;
  }

  sourceQuery.businessType = "";
  sourceQuery.status = "";
  sourceQuery.dateRange = [];
  sourceQuery.keyword = "";
  fetchSourceBills();
  sourceDialogVisible.value = true;
};

const fetchSourceBills = () => {
  // 模拟接口请求，根据供应商筛选源单
  sourceBillList.value = [
    {
      billNo: "CGD20250601001",
      businessType: "purchase",
      billDate: "2025-06-01",
      supplier: selectedSupplier.value.name || "供应商A",
      amount: 5000.0,
      settledAmount: 2000.0,
      unsettledAmount: 3000.0,
      status: "partial",
    },
    {
      billNo: "FYD20250610001",
      businessType: "payment",
      billDate: "2025-06-10",
      supplier: selectedSupplier.value.name || "供应商A",
      amount: 8000.0,
      settledAmount: 0.0,
      unsettledAmount: 8000.0,
      status: "unsettled",
    },
    {
      billNo: "CGD20250615002",
      businessType: "purchase",
      billDate: "2025-06-15",
      supplier: selectedSupplier.value.name || "供应商A",
      amount: 12000.0,
      settledAmount: 12000.0,
      unsettledAmount: 0.0,
      status: "settled",
    },
    {
      billNo: "QTF20250620001",
      businessType: "other",
      billDate: "2025-06-20",
      supplier: selectedSupplier.value.name || "供应商A",
      amount: 3500.0,
      settledAmount: 1500.0,
      unsettledAmount: 2000.0,
      status: "partial",
    },
  ];
};

const handleSourceSelection = (val) => {
  selectedSourceBills.value = val;
};

const confirmSource = () => {
  if (selectedSourceBills.value.length === 0) {
    ElMessage.warning("请选择源单");
    return;
  }

  // 将选择的源单添加到源单表格
  selectedSourceBills.value.forEach((bill) => {
    // 检查是否已存在相同单号的源单
    const exists = sourceTable.value.some(
      (row) => row.sourceNo === bill.billNo
    );
    if (!exists) {
      sourceTable.value.push({
        id: sourceTable.value.length + 1,
        sourceNo: bill.billNo,
        businessType: getBusinessTypeLabel(bill.businessType),
        docDate: bill.billDate,
        docAmount: bill.amount,
        settledAmount: bill.settledAmount,
        unsettledAmount: bill.unsettledAmount,
        currentSettle: 0, // 默认本次核销金额为0
        remark: "",
      });
    }
  });

  sourceDialogVisible.value = false;
};

// 表格操作
const addSettlementRow = () => {
  settlementTable.value.push({
    id: settlementTable.value.length + 1,
    account: "",
    amount: 0,
    method: "",
    no: "",
    remark: "",
  });
};

const deleteSettlementRow = (row) => {
  settlementTable.value = settlementTable.value.filter(
    (item) => item.id !== row.id
  );
};

const addSourceRow = (index) => {
  sourceTable.value.splice(index + 1, 0, {
    id: sourceTable.value.length + 1,
    sourceNo: "",
    businessType: "",
    docDate: "",
    docAmount: 0,
    settledAmount: 0,
    unsettledAmount: 0,
    currentSettle: 0,
    remark: "",
  });
};

const deleteSourceRow = (row) => {
  sourceTable.value = sourceTable.value.filter((item) => item.id !== row.id);
};

// 附件预览
const handlePreview = (file) => {
  console.log("预览附件：", file);
  ElMessage.info(`预览附件: ${file.name}`);
};

// 初始化
onMounted(() => {
  fetchSuppliers();
});
</script>

<style scoped>
.payment-container {
  padding: 32px;
  background: #f9fafb;
}

.header-card {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
}

.required::after {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.el-table {
  --el-table-header-text-color: #303133;
  --el-table-header-background-color: #144288;
  --el-table-row-hover-background-color: #041d43;
}

.el-table__cell {
  white-space: nowrap;
  overflow: visible;
  text-overflow: clip;
}

.overflow-x-auto {
  overflow-x: auto;
}

::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #dd0b0b;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #ba7070;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

@media (max-width: 1024px) {
  .payment-container {
    padding: 16px;
  }

  .header-card .flex {
    flex-direction: column;
    gap: 4px;
  }

  .header-card .flex > div {
    min-width: 100%;
  }
}
</style>